package com.wisdom.system.service.impl.current;

import com.wisdom.system.dao.current.CurrentRoleMapper;
import com.wisdom.system.dao.current.CurrentUserMapper;
import com.wisdom.system.entity.current.CurrentRole;
import com.wisdom.system.entity.current.CurrentUser;
import com.wisdom.system.common.util.ObjectUtil;
import com.wisdom.system.common.util.StringUtil;
import com.wisdom.system.service.current.CurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CurrentUserServiceImpl implements CurrentUserService {

    @Autowired
    CurrentUserMapper currentUserMapper;
    @Autowired
    CurrentRoleMapper currentRoleMapper;

    @Override
    public CurrentUser getCurrentUser() {
        Object obj  = new Object();
        try{
             obj = SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
        }catch (Exception e){
            obj =null;
        }
        // 匿名用户，未登录用户
        if(ObjectUtil.isNull(obj) || "anonymousUser".equals(obj)) {
            return null;
        }
        UserDetails userDetails;
        try {
            userDetails = (UserDetails) obj;
            if(ObjectUtil.isNull(userDetails) || StringUtil.isEmpty(userDetails.getUsername())) {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
        String loginCode = userDetails.getUsername();//获取登录账号
        return getCurrentUser(loginCode);
    }

    @Override
    public CurrentUser getCurrentUser(String loginCode) {
        CurrentUser currentUser = currentUserMapper.getCurrentUser(loginCode);
        if (currentUser != null) {
            String fkUserId = currentUser.getUserId();
            List<CurrentRole> currentRoleList = currentRoleMapper.getCurrentRoleList(fkUserId);
            currentUser.setRoleList(currentRoleList);
        }
        return currentUser;
    }
}
